import React, {useState, useEffect} from 'react';
import {Row, Col ,Card,InputNumber,Divider,Form,Button,message,Popconfirm } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect,history } from 'umi';
import { getScoreTopic,saveScoreInfo} from '../service';
import store from 'store2';
const FormItem = Form.Item;

const Edit = ({match}) => {
  const { obj = {} } = match.params;
  const { programId,id,programName,name } = JSON.parse(obj);
  const [data,setData] = useState([]);
  const [form] = Form.useForm();
  const [loading,setLoading] = useState(false);
  const [sum,setSum] = useState(0);
  const [storageLoading,setStorageLoading] = useState(false);

  useEffect(() => {
    if(programId){
      const fieldsValue = store(`score-edit-` + id);
      getScoreTopic(programId).then(res => {
        setData(res);
      });
      form.setFieldsValue(fieldsValue);
      setSum(fieldsValue ? fieldsValue.sum : 0);
    }
  }, []);

  const onFormCancel = () => {
    form.resetFields();
    history.goBack();
  };

  const compute = async () => {
    const fieldsValue = await form.getFieldsValue();
    let temp = 0;
    Object.keys(fieldsValue).forEach(item => {
      if(typeof fieldsValue[item] === 'number'){
        temp = temp += fieldsValue[item];
      }
    });
    setSum(temp);
  };

  const onFinish = () => {
    setLoading(true);
    const fieldsValue = form.getFieldsValue();
    let array = [];
    Object.keys(fieldsValue).forEach(item => {
      array.push({id:item,score:fieldsValue[item]});
    });
    form.resetFields();
    let temp = {
      id:id,
      scoreTopicScoreDtoArrayList:array
    };
    saveScoreInfo(temp).then((res) => {
      if(res.flag){
        message.success('操作成功！');
        store.remove(`score-edit-` + id);
        onFormCancel();
      }else{
        message.error(`评分保存报错：` + res.error);
      }
      setLoading(false)
    })
  };

  const onFormSave = async () => {
    setStorageLoading(true);
    const fieldsValue = await form.validateFields();
    fieldsValue.sum = sum;
    store(`score-edit-` + id,fieldsValue);
    setStorageLoading(false);
    message.success("评分暂存成功！");
  };

  return (
    <PageHeaderWrapper>
      <Card title={<span>被评分人：<strong style={{paddingRight:'24px'}}>{name}</strong> 评分原因：<strong>{programName}</strong></span>} extra={<span style={{color: '#68B377'}}>请按各项要求给予评分，评分范围可至小数点后一位</span>}>
        <Form form={form}>
          {
            data.map((item, index) => {
              return <Row justify='center' key={index}>
                <Col span={19} style={{paddingTop: '6px'}}>{index + 1}{`、`}{item.title}</Col>
                <Col span={3}>
                  <FormItem>
                    <FormItem name={item.id} noStyle rules={[{required: true, message: '评分不能为空！'}]}>
                      <InputNumber min={1} max={10} step={1} onChange={compute}/>
                    </FormItem>
                    <span style={{paddingLeft: '10px'}}>分</span>
                  </FormItem>
                </Col>
                <Col span={2} style={{paddingTop: '6px', justifyContent: 'center', display: 'flex'}}>满分10分</Col>
                <Divider style={{margin: '0px', marginBottom: '24px'}}/>
              </Row>
            })
          }
          <Row justify='center'>
            <p style={{textAlign: 'center',width:'100%'}}>当前评分总分为 <span style={{color:'#68B377',fontWeight:'bold'}}>{sum}</span> 分</p>
            <Button onClick={() => onFormCancel()} style={{marginRight:'24px'}}>取消</Button>
            <Button onClick={() => onFormSave()} loading={storageLoading} style={{marginRight:'24px'}}>暂存</Button>
            <Popconfirm title={`您的评分总分为${sum}分，是否确认提交？`} onConfirm={onFinish} okText="是" cancelText="否">
              <Button type="primary" loading={loading}>提交</Button>
            </Popconfirm>
          </Row>
        </Form>
      </Card>
    </PageHeaderWrapper>
  )
};

export default connect(() => ({
}))(Edit)
